package com.rjwh.dingdong.client.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;

import com.rjwh.dingdong.client.activity.guide.MainActivity;
import com.rjwh.dingdong.client.activity.webbrowser.OaGameActivity;
import com.rjwh.dingdong.client.application.AppManager;
import com.rjwh.dingdong.client.application.MyApplication;
import com.rjwh.dingdong.client.constant.LocalConstant;
import com.rjwh.dingdong.client.util.AppUtil;
import com.rjwh.dingdong.client.util.LogUtil;
import com.rjwh.dingdong.client.util.UrlUtil;

/**
 * 推送通知栏点击广播
 */
public class NotificationReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        //判断app进程是否存活
        LogUtil.d("isAppLive:" + AppManager.getAppManager().getActivitySize());
        if (AppManager.getAppManager().getActivitySize() >= 1) {
            LogUtil.i("NotificationReceiver", "the app process is alive");
            if (intent != null) {
                String actionurl = intent.getStringExtra("actionurl");
                Intent actionIntent = UrlUtil.handelUrl(context, actionurl, false);
                Intent mainIntent = new Intent(context, MainActivity.class);
                mainIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                if (actionIntent == null) {
                    LogUtil.i("NotificationReceiver", "actionIntent == NULL");
                    context.startActivity(mainIntent);
                } else {
                    //判断当前是否为游戏/绘本全屏界面
                    if (AppUtil.isForeground(context, OaGameActivity.class.getName())) {
                        LogUtil.i("NotificationReceiver", "OaGameActivity start actionIntent");
                        actionIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        context.startActivity(actionIntent);
                    } else {
                        LogUtil.i("NotificationReceiver", "startActivities");
                        Intent[] intents = {mainIntent, actionIntent};
                        context.startActivities(intents);
                    }
                }
            }
        } else {
            LogUtil.i("NotificationReceiver", "the app process is dead");
            if (intent != null) {
                String actionurl = intent.getStringExtra("actionurl");
                Intent launchIntent = context.getPackageManager().
                        getLaunchIntentForPackage(MyApplication.getInstance().packgeName);
                launchIntent.setFlags(
                        Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
                Bundle args = new Bundle();
                args.putString("actionurl", actionurl);
                launchIntent.putExtra(LocalConstant.APP_EXTRA_BUNDLE, args);
                context.startActivity(launchIntent);
            }
        }
    }
}
